﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EPiServer.Security;

namespace EPiServer.Research.VirtualRoles
{

    /// <summary>
    /// This user will be in this role every day in the specified time intervals
    /// "start": starttime in the format hh:mm:ss
    /// "stop": stop time in the format hh:mm:ss
    /// </summary>
    public class TimedRole : VirtualRoleProviderBase
    {
        public TimeSpan StartTime { get; set; }
        public TimeSpan StopTime { get; set; }
        public bool IncludeWeekends { get; set; }

        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            base.Initialize(name, config);
            StartTime = DateTime.Parse(config["start"]).TimeOfDay;
            StopTime = DateTime.Parse(config["stop"]).TimeOfDay;
            IncludeWeekends=false;
            if (config["includeweekends"] != null) IncludeWeekends = bool.Parse(config["includeweekends"]);
        }

        public override bool IsInVirtualRole(System.Security.Principal.IPrincipal principal, object context)
        {
            TimeSpan n = DateTime.Now.TimeOfDay;
            if ((n >= StartTime) && (n <= StopTime))
            {
                if (!IncludeWeekends)
                {
                    if ((DateTime.Now.DayOfWeek == DayOfWeek.Saturday) || (DateTime.Now.DayOfWeek == DayOfWeek.Sunday)) return false;
                }
                return true;
            }
            return false;
        }
    }
}
